package com.gulimall.gulimallorder.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //那到老请求的数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //避免一些无需同步cookie的数据发生空指针
                if(requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest();//老请求
                    //同步请求头中的数据
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步老请求中的cookie
                    requestTemplate.header("Cookie",cookie);
                }
                }

        };
    }
}
